package com.tiles.controller;

import com.tiles.tools.DesUtil;
import com.tiles.tools.Md5Util;
import com.tiles.entity.TilesUser;
import com.tiles.service.TilesUserService;
import com.tiles.tools.SmsCode;
import com.tiles.tools.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import redis.clients.jedis.Jedis;

@Controller
public class RegisterController {
    @Autowired
    private TilesUserService service;


    //注册页面
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    //生成短线验证码
    @PostMapping("/smsCode")
    public void smsCode(@RequestParam String phone){
        Jedis jedis = new Jedis();
        String smsCode = SmsCode.RandomCode();
        jedis.setex(phone, 180, smsCode);
        jedis.close();
        try {
            SmsUtil.sendSms(phone, smsCode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/register")
    public String register(@RequestBody TilesUser tilesUser,@RequestParam String SmsCode, Model model) throws Exception {
        Jedis jedis = new Jedis();
        if(tilesUser.getTilesPassword()!=null && tilesUser.getTilesUsername()!=null){
            if (SmsCode!=null && jedis.get(tilesUser.getPhone())==SmsCode) {
                System.out.println("短信验证通过");
                if(service.selectByUserName(tilesUser.getTilesUsername())>0){
                    model.addAttribute("msg", "用户已注册");
                    return registerPage();
                }else {
                    service.insertTilesUser(tilesUser);
                    return "success";
                }
            }else {
                model.addAttribute("msg", "验证码不正确");
                return registerPage();
            }
        }else {
            model.addAttribute("msg", "用户名密码不能为空");
            return registerPage();
        }

    }
}
